class Bird {
    constructor() {
        this.y = 100;
        this.x = 100
        this.width = 100 / 3;
        this.height = 30;
        //三种形态0,1,2
        this.state = 0;
        this.dy = 8;
        //开始掉落的帧数
        this.dropStartFrame = game.frameUtil.currentFrame;

        //鸟的旋转角度
        this.ro = 0;
        //添加监听
        this.bindClickListener();
        //鸟的状态
        this.status = 0 //0为下降，1位上升
        //鸟的上升的位移
        this.goUp = 7;

        this.deltaY = 1;
        //鸟的掉落系数
        this.downRatio = 0.003;


    }
    update() {
        //鸟每五帧运行一次
        if (game.frameUtil.currentFrame % 5 === 0) {
            this.state > 1 ? this.state = 0 : this.state++;
        }
        //如果状态为下降
        if (this.status === 0) {
            this.dy = this.downRatio * (game.frameUtil.currentFrame - this.dropStartFrame) ** 2
            this.ro += 1;
            // console.log(game.frameUtil.currentFrame);
            // console.log(this.dropStartFrame);
        } else if (this.status === 1) {
            //上升
            this.deltaY += 2
            //小鸟上升的极限就是上升那一瞬间+120
            this.dy = -this.goUp + this.deltaY ** 0.5;
            this.ro = -30;
            if (this.dy > 0) {
                //下降
                this.status = 0;
                this.dropStartFrame = game.frameUtil.currentFrame;
                this.deltaY = 1;

            }
        }
        this.y += this.dy;
        // console.log("我运行了一次");

        //规定飞的范围
        //天花板，地板检测
        if (this.y < -5) this.y = 0;
        if (this.y > game.canvas.height - 110) {
            game.audio.setAttribute('src', 'music/No.mp3');
            game.audio.load();
            game.audio.play();
            game.suspend();
            game.restart();
        }

    }
    render() {
        game.pen.save();
        game.pen.translate(this.x + this.width / 2, this.y + this.height / 2)
        game.pen.rotate(Math.PI / 180 * this.ro)
        game.pen.translate(-(this.x + this.width / 2), -(this.y + this.height / 2))
        game.pen.drawImage(game.images.bird, this.state * this.width, 0, this.width, this.height, this.x, this.y, this.width, this.height);
        game.pen.restore();
    }
    bindClickListener() {
        let self = this;
        //监听pc鼠标点击事件
        game.canvas.addEventListener("mousedown", function () {
            self.status = 1;
            // self.dy = -6;
            self.deltaY = 1;
            // console.log(self.status);
        });
        //监听pc键盘空格事件
        document.onkeydown = function (event) {
            if (event.code === "Space") {
                self.status = 1;
                self.deltaY = 1;
            }
        }
        //监听移动端事件
        game.canvas.ontouchstart = function () {
            self.status = 1;
            self.deltaY = 1;
        }
    }
}